package com.ayitubie.refuelweb.config.interceptor.loginUserInterceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginUserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LoginUser loginUser = getUser(request, response);
        UserContext.setUser(loginUser);
        return true;
    }

    private LoginUser getUser(HttpServletRequest request, HttpServletResponse response) {
        String token = request.getHeader("Authorization");
        LoginUser loginUser = new LoginUser();
        if (token != null) {
            String userId = token.substring(32);
            loginUser.setUserId(Integer.parseInt(userId));
        }
        return loginUser;
    }

}
